//
//  LoginViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/27.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//
//  登录主界面
import UIKit
import DynamicBlurView
import PKHUD

import Alamofire
import SwiftyJSON

class LoginViewController: BaseViewController {
    @IBOutlet weak var bgImageView: UIImageView!
    
    @IBOutlet weak var wbBtn: UIButton!
    @IBOutlet weak var qqBtn: UIButton!
    @IBOutlet weak var wxBtn: UIButton!
    @IBOutlet var thirdButtons: [UIButton]!
    @IBOutlet weak var mainScrollView: UIScrollView!
    @IBOutlet weak var phoneTextField: UITextField!
    @IBOutlet weak var pwTextField: UITextField!
    @IBOutlet var borderViews: [UIView]!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if MineInfoModel.share.isLogin {
            MineInfoModel.share.exitLogin()
        }
        setUI()
        // Do any additional setup after loading the view.
    }
    
    // MARK: 设置UI
    func setUI() {
        titleLabel(text: "登录", nil)
        
        let _ = thirdButtons.map({
            $0.layer.cornerRadius = $0.height / 2
            $0.layer.borderColor = UIColor(hex: 0x86878B).cgColor
            $0.layer.borderWidth = 1
        })
        
        let _ = borderViews.map({
            $0.layer.borderColor = UIColor.white.cgColor
            $0.layer.borderWidth = 1
        })
        
        phoneTextField.attributedPlaceholder = NSAttributedString(string: "请输入手机号码", attributes: [NSAttributedStringKey.foregroundColor : UIColor(hex: 0xB6B6B6)])
        pwTextField.attributedPlaceholder = NSAttributedString(string: "请输密码", attributes: [NSAttributedStringKey.foregroundColor : UIColor(hex: 0xB6B6B6)])
        
        let blurView = DynamicBlurView(frame: bgImageView.bounds)
        blurView.blurRadius = 10
        view.insertSubview(blurView, aboveSubview: bgImageView)
        
        if UMSocialManager.default().isInstall(UMSocialPlatformType.wechatSession) {
            wxBtn.isHidden = false
        }
        if UMSocialManager.default().isInstall(UMSocialPlatformType.QQ) {
            qqBtn.isHidden = false
        }
        if UMSocialManager.default().isInstall(UMSocialPlatformType.sina) {
            wbBtn.isHidden = false
        }
    }
    
    override func setNavigation() {
    }
    // MARK: - 登录点击
    @IBAction func loginTap(_ sender: UIButton) {
        let textPhone = phoneTextField.text
        if (textPhone?.count == 0) {
            self.showToast(msg: "请输入手机号码")
            return
        }
        let textPwd = pwTextField.text
        if (textPwd?.count == 0) {
            self.showToast(msg: "请输入密码")
            return
        }
        let requesturl = "\(BaseURL)\(loginUrl)"
        let parameter:[String : Any] = ["mp":phoneTextField.text!,
                                        "psw":pwTextField.text!,
                                        "type": "0"]
        Alamofire.request(requesturl, method: .post,
                          parameters: parameter,
                          encoding: URLEncoding.default,
                          headers: nil).responseJSON {
                            (response) in
                            HUD.hide()
                            if(response.error == nil){
                                if let result = response.result.value as? NSDictionary
                                {
                                    
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg: "登录成功")
                                        let dic = json["data"].dictionary
                                        var userModel = UserInfoModel(fromDic: dic!)
                                        if let dict = json["data"]["grade"].dictionary {
                                            userModel.initGrade(dic: dict)
                                        }
                                        //注册成功后返回用户信息，需要保存用户信息
                                        
                                        let mineInfoModel = MineInfoModel.share
                                        mineInfoModel.userInfModel = userModel
                                        mineInfoModel.token = userModel.token!
                                        mineInfoModel.isLogin = true
                                        mineInfoModel.saveUserData(userinfo: userModel.toDictionary() as NSDictionary)
                                        mineInfoModel.loadUserData()
                                        
                                        self.navigationController?.popToRootViewController(animated: true)
                                        
                                    }
                                    else{
                                        self.showToast(msg: json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg: "请求失败")
                            }
                            
        }
        HUD.show(.label("加载中..."))
    }
    // MARK: - 注册点击
    @IBAction func registTap(_ sender: UIButton) {
        
        let registVC = RegistViewController(nibName: "\(RegistViewController.self)", bundle: nil)
        navigationController?.pushViewController(registVC, animated: true)
        
    }
    // MARK: - 忘记密码点击
    @IBAction func forgetPwTap(_ sender: UIButton) {
        let retrievePasswordVC = RetrievePasswordViewController(nibName: "\(RetrievePasswordViewController.self)", bundle: nil)
        navigationController?.pushViewController(retrievePasswordVC, animated: true)
        
        
    }
    // MARK: - 三方登录点击 tag 0微博 - 1QQ - 2微信
    @IBAction func threePartyLoginTaps(_ sender: UIButton) {
        if sender.tag == 0 {
            UMSocialManager.default().getUserInfo(with: UMSocialPlatformType.sina, currentViewController: nil, completion: { (result, error) in
                if (result != nil) {
                    let userInfo = result as! UMSocialUserInfoResponse
        
                    self.thirdsPartyRedictToOurNet(openid: userInfo.uid, type: "3")
           
                }else
                {
                    print("--",error.debugDescription)
                }
            })
        }
        else if(sender.tag == 1){
            UMSocialManager.default().getUserInfo(with: UMSocialPlatformType.QQ, currentViewController: nil, completion: { (result, error) in
                if (result != nil) {
                    let userInfo = result as! UMSocialUserInfoResponse
                    self.thirdsPartyRedictToOurNet(openid: userInfo.usid, type: "1")
                }else
                {
                    print("--",error.debugDescription)
                }
            })
        }
        else{
            UMSocialManager.default().getUserInfo(with: UMSocialPlatformType.wechatSession, currentViewController: nil, completion: { (result, error) in
                if (result != nil) {
                    //获取用户的个人信息
                    let userInfo = result as! UMSocialUserInfoResponse
                    print("1111")
                    self.thirdsPartyRedictToOurNet(openid: userInfo.unionId, type: "2")
//                    userInfo.uid...
                    //调用本地登录接口
                }else
                {
                    print("--",error.debugDescription)
                }
               
            })
        }
    }
    
    func thirdsPartyRedictToOurNet(openid: String, type: String) -> Void {
        let requesturl = "\(BaseURL)\(loginUrl)"
        let parameter:[String : Any] = ["bindId":openid,
                                        "type": type]
        Alamofire.request(requesturl, method: .post,
                          parameters: parameter,
                          encoding: URLEncoding.default,
                          headers: nil).responseJSON {
                            (response) in
                            if(response.error == nil){
                                if let result = response.result.value as? NSDictionary
                                {
                                    
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg: "登录成功")
                                        let dic = json["data"].dictionary
                                        var userModel = UserInfoModel(fromDic: dic!)
                                        if let dict = json["data"]["grade"].dictionary {
                                            userModel.initGrade(dic: dict)
                                        }
                                        //注册成功后返回用户信息，需要保存用户信息
                                        
                                        let mineInfoModel = MineInfoModel.share
                                        mineInfoModel.userInfModel = userModel
                                        mineInfoModel.token = userModel.token!
                                        mineInfoModel.isLogin = true
                                        mineInfoModel.saveUserData(userinfo: userModel.toDictionary() as NSDictionary)
                                        mineInfoModel.loadUserData()
                                        
                                        self.navigationController?.popToRootViewController(animated: true)
                                        
                                    }
                                    else{
                                        if json["code"].int == 110 {
                                            self.showToast(msg: json["message"].string!)
                                            let registVC = RegistViewController(nibName: "\(RegistViewController.self)", bundle: nil)
                                            registVC.type = type
                                            registVC.bindid = openid
                                            self.navigationController?.pushViewController(registVC, animated: true)
                                        }else{
                                            self.showToast(msg: json["message"].string!)
                                        }
                                    }
                                }
                            }else{
                                self.showToast(msg: "请求失败")
                            }
                            
        }
    }
}

